package com.baizhi.elastic.dao.impl;

import com.baizhi.elastic.dao.PostRepository;
import com.baizhi.elastic.entity.Post;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Component
public class PostRepositoryImpl implements PostRepository {
	@Autowired
	private ElasticsearchTemplate elasticsearchTemplate;

	@Override
	public List<Post> selectPostByNameAndHighlightAndPageable(String name, String value, int page, int size) {

		HighlightBuilder.Field field = new HighlightBuilder.Field("*").preTags("<span style='color red'>").postTags("</span>");

		NativeSearchQuery queryBuilder = new NativeSearchQueryBuilder()
			.withQuery(QueryBuilders.termQuery(name,value))
			.withPageable(PageRequest.of(page,size))
			.withHighlightFields(field)
			.build();

		SearchResultMapper resultMapper = new SearchResultMapper() {
			@Override
			public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
				List<Post> posts = new ArrayList<>();
				SearchHits hits = searchResponse.getHits();
//				得到所有的内容
				SearchHit[] hits1 = hits.getHits();

//				对结果进行遍历

				for(SearchHit hit : hits1){
//					得到所有的结果
					Map<String, Object> sourceAsMap = hit.getSourceAsMap();
					Map<String, HighlightField> fieldMap = hit.getHighlightFields();

					Post post = new Post();

//					遍历结果的map
					for(Map.Entry entry : sourceAsMap.entrySet()){
						String key = (String)entry.getKey();
						HighlightField highlightField = fieldMap.get(key);
						if(highlightField != null){
							if("content".equals(key)){
								post.setTitle(highlightField.fragments()[0].toString());
							}
						}else{
							Object o = sourceAsMap.get(key);
							if("id".equals(key)){
								post.setId(o.toString());
							}else if("title".equals(key)){
								post.setTitle(o.toString());
							}else if("userId".equals(key)){
								post.setUserId(Integer.parseInt(o.toString()));
							}else if("weight".equals(key)){
								post.setWeight(Integer.parseInt(o.toString()));
							}
						}

					}
					posts.add(post);
				}
				return new AggregatedPageImpl<T>((List<T>) posts);
			}

		};
		AggregatedPage<Post> posts = elasticsearchTemplate.queryForPage(queryBuilder, Post.class, resultMapper);
		return posts.getContent();
	}
}
